package com.code.aspect;

import com.code.commons.enums.ResultCode;
import com.code.commons.exceptions.BusinessException;
import com.code.commons.util.StringUtil;
import com.code.commons.web.annotations.SuperAdmin;
import com.code.user.client.UserClient;
import com.code.user.model.bo.LoginUser;
import com.code.user.model.po.User;
import com.code.user.token.helper.LoginTokenHelper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/**
 * 超级管理员切面
 *
 * @author tangyifei
 * @since 2020年2月7日11:54:40
 **/
@Aspect
@Configuration
@Slf4j
public class SuperAdminAspect {

    @Resource
    UserClient userClient;

    @Around("execution(* com.code.web ..*(..) )")
    public Object interceptor(ProceedingJoinPoint joinPoint) throws Throwable {

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
//        Class<?> targetClass = method.getDeclaringClass();
        SuperAdmin superAdmin = method.getAnnotation(SuperAdmin.class);
        if (null != superAdmin) {
            LoginUser loginUser = LoginTokenHelper.getLoginUserFromRequest();
            if (null != loginUser && StringUtil.isNotEmpty(loginUser.getId())) {
                User user = userClient.getById(loginUser.getId());
                if (null != user) {
                    int isAdmin = user.getIsAdmin();
                    if (isAdmin != 1) {
                        throw new BusinessException(ResultCode.SUPER_ADMIN_ERROR);
                    }
                }
            }
        }
        return joinPoint.proceed();
    }

}
